package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 */
public class ReverseNodesInKGroup3 {

    public static void main(String[] args) {
        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
        ListNode.print(e1);
        ListNode reverse = new ReverseNodesInKGroup3().reverseKGroup(e1, 2);
        ListNode.print(reverse);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = dummy;
        while (cur.next != null) {
            for (int i = 0; i < k && cur != null; i++) {
                cur = cur.next;
            }
            if (cur == null) {
                break;
            }
            ListNode curStart = pre.next;
            ListNode next = cur.next;
            cur.next = null;
            pre.next = reverse(curStart);
            curStart.next = next;
            pre = curStart;
            cur = curStart;
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
